<template>
  <div>
    <!-- Form -->

    <el-dialog
      :title="info.isAdd ? '添加' : '修改'"
      :visible.sync="info.isshow"
      @close="close"
      @opened="opened"
      >{{ form }}
      <el-form :model="form">
        <el-form-item label="一级分类" :label-width="formLabelWidth">
          <el-select
            v-model="form.first_cateid"
            placeholder="请选择一级分类"
            @change="changeId(form.first_cateid)"
          >
            <el-option
              v-for="item in arr"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="二级分类" :label-width="formLabelWidth">
          <el-select v-model="form.second_cateid" placeholder="请选择二级分类">
            <el-option
              v-for="item in arrChildren"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="form.goodsname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价格" :label-width="formLabelWidth">
          <el-input v-model="form.market_price" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="上传图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-change="changeImg"
          >
            <img v-if="imgUrl" :src="imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="商品规格" :label-width="formLabelWidth">
          <el-select
            @change="changeSpecsId"
            v-model="form.specsid"
            placeholder="请选择商品规格"
          >
            <el-option
              v-for="item in arrSpecs"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        ,
        <el-form-item label="规格属性" :label-width="formLabelWidth">
          <el-select v-model="form.specsattr" multiple placeholder="请选择">
            <el-option
              v-for="item in arrSpecsChildren"
              :key="item.id"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否新品" :label-width="formLabelWidth">
          <el-radio v-model="form.isnew" :label="1">是</el-radio>
          <el-radio v-model="form.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否热卖" :label-width="formLabelWidth">
          <el-radio v-model="form.ishot" :label="1">是</el-radio>
          <el-radio v-model="form.ishot" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="商品描述" :label-width="formLabelWidth">
          <div id="editor" v-if="info.isshow"></div>
        </el-form-item>
        <el-form-item>
          <el-switch
            v-model="form.status"
            inactive-text="状态"
            :active-value="1"
            :inactive-value="2"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button @click="cancel">取 消</el-button> -->
        <el-button type="primary" @click="add" v-if="info.isAdd"
          >添 加</el-button
        >
        <el-button type="primary" @click="getOne" v-else>修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqgoodsadd,
  reqgoodsinfo,
  reqgoodsedit,
  reqcatelist,
  reqspecslist,
  reqgoodslist,
} from "../../../http/api";
import path from "path";
import E from "wangeditor";

import { successAlert } from "../../../utils/alert";
export default {
  props: ["info"],
  data() {
    return {
      form: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        description: "", //m描述
        specsid: "",
        specsattr: "", //"['白色','黑色']"
        isnew: "",
        ishot: "",
        img: "",
        status: 1,
      },
      // Specification:[],
      arr: [],
      imgUrl: "",
      arrSpecsChildren: '',
      arrSpecs: '',
      arrChildren: [],
      dialogFormVisible: true,
      Attributes: [],
      formLabelWidth: "120px",
    };
  },

  mounted() {
    //请求顶级分类
    reqcatelist({ istree: true }).then((res) => {
      if (res.data.code == 200) {
        this.arr = res.data.list;
      }
    });
    reqspecslist({ size: 100, page: 1 }).then((res) => {
      if (res.data.code == 200) {
        this.arrSpecs = res.data.list;
      }
    });
    
  },
  methods: {
    setForm() {
      this.form = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        description: "", //m描述
        specsid: "",
        specsattr: "", //"['白色','黑色']"
        isnew: "",
        ishot: "",
        img: "",
        status: 1,
      };
      
      this.arrSpecsChildren= '';
      // this.arrSpecs= [];
      this.arrChildren= '';
      this.secondCateList = [];
      // this.arr = [];
      this.imgUrl = "";
      //清除编辑器内容
      this.editor.txt.html("");
    },
    //删除规格属性框
    del(e) {
      this.arr.splice(e, 1);
    },
    //请求列表数据
    add() {
      //由于后端要的是字符串 现在得到的是数组所以需要先拷贝规格属性
      let strData = {
        ...this.form,
        specsattr: JSON.stringify(this.form.specsattr),
        description: this.editor.txt.html(),
      };

      if (this.info.isAdd) {
        reqgoodsadd(strData).then((res) => {
          if (res.data.code == 200) {
            //弹成功
            successAlert(res.data.msg);
            //清空form
            this.setForm();
            //弹框消失
            this.info.isshow = false;
            //列表刷新
            this.$emit("init");
          }
        });
      } else {
        reqgoodsedit(strData).then((res) => {
          if (res.data.code == 200) {
            //弹成功
            successAlert(res.data.msg);
            //清空form
            this.setForm();
            //弹框消失
            this.info.isshow = false;
            //列表刷新
            this.$emit("init");
          }
        });
      }
    },
    

    //上传图片
    changeImg(file) {
      //判断上传文件是否是图片
      let format = ["jpg", "gif", "tga", "svg", "webp", "png", "bmp"];
      let imgName = format.includes(path.extname(file.raw.name).split(".")[1]);
      if (!imgName) {
        errorAlert("请上传正确的文件格式");
        ruturn;
      }
      //判断上传文件大小 大于2m不予上传
      if (file.size > 5 * 1024 * 1024) {
        errorAlert("请上传小于2m的图片");
        ruturn;
      }
      this.imgUrl = URL.createObjectURL(file.raw);
      console.log(file);
      console.log(file.raw);
      this.form.img = file.raw;
    },
    //请求一条要修改的数据
    getOne(id) {
      reqgoodsinfo({ id: id }).then((res) => {
        if (res.data.code == 200) {
          this.form = res.data.list;
          this.imgUrl =this.$pre+this.form.img;
          this.getCateList();
          this.getArr();
          this.form.specsattr = JSON.parse(this.form.specsattr);
          // this.arr = this.form.attrs.map((item) => ({ data: item }));
        }
      });
//给编辑器赋值

          /*
          动画：  2s
          请求： 1s 3s  
                请求快，1s请回来了，2s的时候编辑器才创建，那么此刻，编辑器就是undefined，此刻不给编辑器赋值。
                    应该在编辑器创建好的时候赋值。
                请求慢，3s请回来，2s编辑器已经创建好了，此刻可以给编辑器赋值
          
          */ 
       if(this.editor){
            this.editor.txt.html(this.form.description)
          }
        
    },

    //如果是编辑的蒙层关闭了 清空form
    close() {
      if (this.info.isAdd == false) {
        this.setForm();
      }
    },
    //弹框出现完成
    opened() {
      //创建编辑器
      this.editor = new E("#editor");
      this.editor.create();
      // 给编辑器赋值
      this.editor.txt.html(this.form.description);
    },
    //选择顶级分类的时候请求相应的二级分类
    changeId() {
      //清空二级分类的值
      this.form.second_cateid = "";
      this.getCateList();
      
    },
    //获取二级分类列表
    getCateList(){
      reqcatelist({ pid:  this.form.first_cateid }).then((res) => {
        this.arrChildren = res.data.list ? res.data.list : [];
      });
    },
    getArr() {
      //规格表单事件触发相应的规格属性
      let xx = this.arrSpecs.find((item) => item.id == this.form.specsid);
      this.arrSpecsChildren = xx ? xx.attrs : [];
    },
    // 修改了商品规格
    changeSpecsId() {
      //清空规格属性的值
      this.form.specsattr = [];
      this.getArr();
    },
  },
};
</script>

<style>
.el-switch {
  margin-left: 80px;
}
.flexbtn {
  display: flex;
}
.flexbtn .el-input {
  flex: 1;
}

.el-switch {
  margin-left: 80px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
